<template>
  <div>
    <Top></Top>
    <Header></Header>
    <el-row>
      <!-- span:占多少栏   offset：向右偏移多少栏 -->
      <el-col :span="16" :offset="4">
        <el-row :gutter="20">
          <!-- 图片 -->
          <el-col :span="8">
            <img :src="$imgPrefix + kill.image" alt="">
          </el-col>
          <!-- 信息、操作 -->
          <el-col :span="16">
            <p><b>{{kill.gname}}</b></p>
            <p><span>原价：</span>{{kill.price}}</p>
            <p><span>秒杀价：</span>{{kill.killPrice}}</p>
            <p><span>库存：</span>{{kill.num}}</p>
            <el-row v-if="isConsumer()">
              <el-button type="danger" @click="buyNow">立即购买</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>  
    <Footer></Footer>
  </div>
</template>

<script>
import Top from './commons/top.vue'
import Header from './commons/header.vue'
import Footer from './commons/footer.vue'

export default{
  data(){
    return{
      kid: this.$route.params.kid,
      kill: null,
      num: 1,
      user: JSON.parse(localStorage.getItem("user")),
      ws:null
    }
  },
  components: {
    // 2.注册
    Top,
    Header,
    Footer,
  },
  mounted(){
    this.$axios.get("/kill/findById/" + this.kid).then(res =>{
      this.kill = res.data.data
    })
  },
  methods:{
    buyNow(){
      
      //建立websocket连接
      let url="ws://localhost:8080/WebSocketHandler/" + this.user.id
      this.ws = new WebSocket(url)
      //判断是否连接成功, ws不是null,如果失败ws就是null
      if(this.ws){
        console.log("连接成功")
        //指定得到消息的事件
        this.ws.onmessage = function(res){
        console.log(res)
        }
        this.$axios.post("/kill/order/" + this.kid).then(res => {
        if(res.data.code == 200){
          // this.$router.push("/killConfirm/" + res.data.data)
        }
      })
      }else{
        console.log("连接失败")
      }
    },
    isConsumer(){
      // 得到角色列表
      if(this.user.roleList){
        for(let i = 0; i < this.user.roleList.length; i++){
          let role =this.user.roleList[i];
          if(role.name == 'consumer'){
            return true
          }
        }
        return false
      }
    }
  }
}
</script>
<style scoped>
p{
  margin-bottom: 20px;
}
</style>